package com.guaoran.source.zookeeper.thread;

import com.guaoran.source.zookeeper.common.RpcRequest;
import com.guaoran.source.zookeeper.common.StringUtils;
import com.sun.corba.se.impl.ior.ObjectAdapterIdNumber;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/14 12:45
 */
public class ProcessThread implements Runnable{
    private Socket socket;
    private Map<String,Object> registerCenterMap;
    public ProcessThread(Socket socket, Map<String,Object> registerCenterMap) {
        this.socket = socket;
        this.registerCenterMap = registerCenterMap;
    }

    @Override
    public void run() {
        //TODO 处理客户端请求
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        try {
            //获得客户端的请求
            inputStream = new ObjectInputStream(socket.getInputStream());
            RpcRequest request = (RpcRequest) inputStream.readObject();
            //处理请求，并将返回结果返回给客户端
            Object invokeResult = invoke(request);
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(invokeResult);
            //刷新缓冲区并关闭流
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            throw new RuntimeException("处理客户端请求失败:"+e);
        }
    }

    /**
     * 通过反射去处理请求
     * @param request
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private Object invoke(RpcRequest request) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String serviceName = request.getClassName();
        String methodName = request.getMethodName();
        Object[] parames = request.getParams();
        Class<?>[] types = new Class[parames.length];
        for (int i = 0; i < types.length; i++) {
            types[i] = parames[i].getClass();
        }
        String version = request.getVersion();
        //根据服务名称获得服务地址
        if (StringUtils.isNotEmpty(version)){
            serviceName += "-" + version;
        }
        Object service = registerCenterMap.get(serviceName);
        Method method = service.getClass().getMethod(methodName,types);
        return method.invoke(service,parames);
    }
}
